import React, { useState, useEffect } from 'react';
import {
  Card,
  Typography,
  Row,
  Col,
  Avatar,
  Tag,
  Button,
  Space,
  Descriptions,
  Statistic,
  Table,
  Tabs,
  message,
  Spin,
  Modal,
  Popconfirm,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  EditOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  CheckOutlined,
  CloseOutlined,
  StopOutlined,
  PlayCircleOutlined,
  ShopOutlined,
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ShopService } from '../../services/shopService';
import { ProductService } from '../../services/productService';
import { Shop } from '../../types';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

const ShopDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const [shop, setShop] = useState<Shop | null>(null);
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<any>(null);
  const [products, setProducts] = useState<any[]>([]);
  const [loadingProducts, setLoadingProducts] = useState(false);

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '店铺管理', path: '/shops' },
      { title: '店铺详情' },
    ]));

    if (id) {
      loadShop();
      loadShopStats();
      loadShopProducts();
    }
  }, [dispatch, id]);

  const loadShop = async () => {
    if (!id) return;

    try {
      setLoading(true);
      console.log('正在加载店铺详情，ID:', id);
      const shopData = await ShopService.getShop(id);
      console.log('加载的店铺数据:', shopData);
      setShop(shopData);
    } catch (error) {
      message.error('加载店铺详情失败');
      console.error('加载店铺详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadShopStats = async () => {
    if (!id) return;

    try {
      const statsData = await ShopService.getShopStats(id);
      setStats(statsData);
    } catch (error) {
      console.error('加载店铺统计失败:', error);
    }
  };

  const loadShopProducts = async () => {
    if (!id) return;

    try {
      setLoadingProducts(true);
      const response = await ShopService.getShopProducts(id, { page: 1, limit: 10 });
      setProducts(response.data || []);
    } catch (error) {
      console.error('加载店铺商品失败:', error);
    } finally {
      setLoadingProducts(false);
    }
  };

  const handleApprove = async () => {
    if (!id) return;
    try {
      await ShopService.approveShop(id, { status: 'approved' });
      message.success('店铺审核通过');
      loadShop();
    } catch (error) {
      message.error('审核失败');
    }
  };

  const handleReject = async () => {
    if (!id) return;
    try {
      await ShopService.approveShop(id, { status: 'rejected', reason: '不符合要求' });
      message.success('店铺审核拒绝');
      loadShop();
    } catch (error) {
      message.error('审核失败');
    }
  };

  const handleSuspend = async () => {
    if (!id) return;
    try {
      await ShopService.suspendShop(id, '违规操作');
      message.success('店铺已暂停');
      loadShop();
    } catch (error) {
      message.error('暂停失败');
    }
  };

  const handleResume = async () => {
    if (!id) return;
    try {
      await ShopService.resumeShop(id);
      message.success('店铺已恢复');
      loadShop();
    } catch (error) {
      message.error('恢复失败');
    }
  };

  const handleDelete = async () => {
    if (!id) return;
    try {
      await ShopService.deleteShop(id);
      message.success('店铺删除成功');
      navigate('/shops');
    } catch (error: any) {
      console.error('删除失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
      message.error(errorMessage);
    }
  };

  // 删除商品
  const handleDeleteProduct = async (productId: string, productName: string) => {
    try {
      await ProductService.deleteProduct(productId);
      message.success(`商品"${productName}"删除成功`);
      loadShopProducts(); // 重新加载商品列表
    } catch (error: any) {
      console.error('删除商品失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '删除商品失败';
      message.error(errorMessage);
    }
  };

  const getStatusTag = (status: any) => {
    const statusStr = String(status || 'unknown');
    const statusConfig = {
      active: { color: 'green', text: '正常' },
      pending: { color: 'orange', text: '待审核' },
      suspended: { color: 'red', text: '已暂停' },
      inactive: { color: 'gray', text: '已停用' },
    };
    const config = statusConfig[statusStr as keyof typeof statusConfig] || { color: 'gray', text: statusStr };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getTypeTag = (type: any) => {
    const typeStr = String(type || 'unknown');
    const typeConfig = {
      official: { color: 'blue', text: '官方' },
      flagship: { color: 'purple', text: '旗舰' },
      authorized: { color: 'green', text: '授权' },
      personal: { color: 'default', text: '个人' },
    };
    const config = typeConfig[typeStr as keyof typeof typeConfig] || { color: 'default', text: typeStr };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const productColumns: ColumnsType<any> = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.images?.[0] || ''} size={40} style={{ marginRight: 8 }} />
          <div>
            <div>{String(text || '未知商品')}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>{String(record.brand || '')}</Text>
          </div>
        </div>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${(Number(price) || 0).toFixed(2)}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (stock) => Number(stock) || 0,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusStr = String(status || 'inactive');
        return (
          <Tag color={statusStr === 'active' ? 'green' : 'red'}>
            {statusStr === 'active' ? '上架' : '下架'}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => navigate(`/products/${record._id || record.id}`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个商品吗？"
            description={`删除后无法恢复，商品"${String(record.name || '未知商品')}"将被永久删除。`}
            onConfirm={() => handleDeleteProduct(record._id || record.id, String(record.name || '未知商品'))}
            okText="确定删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button
              type="link"
              icon={<DeleteOutlined />}
              size="small"
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <p>加载店铺详情...</p>
      </div>
    );
  }

  if (!shop) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <p>店铺不存在</p>
        <Button onClick={() => navigate('/shops')}>返回列表</Button>
      </div>
    );
  }

  return (
    <div>
      {/* 头部操作栏 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/shops')}
        >
          返回列表
        </Button>

        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => navigate(`/shops/${id}/edit`)}
          >
            编辑店铺
          </Button>

          {shop.status === 'pending' && (
            <>
              <Button
                type="primary"
                icon={<CheckOutlined />}
                style={{ backgroundColor: 'green' }}
                onClick={handleApprove}
              >
                审核通过
              </Button>
              <Button
                danger
                icon={<CloseOutlined />}
                onClick={handleReject}
              >
                审核拒绝
              </Button>
            </>
          )}

          {shop.status === 'active' && (
            <Button
              icon={<StopOutlined />}
              style={{ color: 'orange', borderColor: 'orange' }}
              onClick={handleSuspend}
            >
              暂停店铺
            </Button>
          )}

          {shop.status === 'suspended' && (
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              style={{ backgroundColor: 'green' }}
              onClick={handleResume}
            >
              恢复店铺
            </Button>
          )}

          <Popconfirm
            title="确定要删除这个店铺吗？"
            description={`删除后无法恢复，店铺"${shop.name}"的所有数据将被永久删除。${shop.stats?.totalProducts > 0 ? '注意：该店铺还有商品，删除可能失败。' : ''}`}
            onConfirm={handleDelete}
            okText="确定删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button danger icon={<DeleteOutlined />}>
              删除店铺
            </Button>
          </Popconfirm>
        </Space>
      </div>

      {/* 店铺基本信息 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={16}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 24 }}>
              <Avatar src={shop.logo || ''} size={80} style={{ marginRight: 16 }} />
              <div style={{ flex: 1 }}>
                <Title level={3} style={{ margin: 0, marginBottom: 8 }}>
                  {String(shop.name || '未知店铺')}
                  {getTypeTag(shop.type)}
                  {getStatusTag(shop.status)}
                </Title>
                <Paragraph style={{ color: '#666', marginBottom: 16 }}>
                  {String(shop.description || '暂无描述')}
                </Paragraph>
                <Space>
                  <Text><UserOutlined /> 店主: {String(shop.owner?.name || shop.owner || '未知')}</Text>
                  <Text>创建时间: {shop.createdAt ? new Date(shop.createdAt).toLocaleDateString() : '未知'}</Text>
                </Space>
              </div>
            </div>

            {shop.banner && (
              <div style={{ marginBottom: 16 }}>
                <img
                  src={String(shop.banner)}
                  alt="店铺横幅"
                  style={{ width: '100%', maxHeight: 200, objectFit: 'cover', borderRadius: 4 }}
                />
              </div>
            )}

            <Descriptions column={2} bordered>
              <Descriptions.Item label="店铺类型">
                {getTypeTag(shop.type)}
              </Descriptions.Item>
              <Descriptions.Item label="店铺状态">
                {getStatusTag(shop.status)}
              </Descriptions.Item>
              <Descriptions.Item label="经营分类">
                {Array.isArray(shop.categories) && shop.categories.map(cat => (
                  <Tag key={cat} style={{ margin: '2px' }}>{String(cat)}</Tag>
                ))}
                {(!shop.categories || shop.categories.length === 0) && (
                  <span style={{ color: '#999' }}>暂无分类</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="店铺标签">
                {Array.isArray(shop.tags) && shop.tags.map(tag => (
                  <Tag key={tag} color="blue" style={{ margin: '2px' }}>{String(tag)}</Tag>
                ))}
                {(!shop.tags || shop.tags.length === 0) && (
                  <span style={{ color: '#999' }}>暂无标签</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="店铺评分">
                {(() => {
                  const rating = shop.rating?.overall || shop.rating || 0;
                  const ratingNum = typeof rating === 'number' ? rating : parseFloat(rating) || 0;
                  return `${ratingNum.toFixed(1)} 分 (${shop.reviewCount || 0} 评价)`;
                })()}
              </Descriptions.Item>
              <Descriptions.Item label="认证状态">
                {shop.certification?.isVerified ? (
                  <Tag color="green">已认证</Tag>
                ) : (
                  <Tag color="orange">未认证</Tag>
                )}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        <Col span={8}>
          {/* 统计信息 */}
          <Card title="店铺统计" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="商品数量"
                  value={shop.stats?.totalProducts || 0}
                  suffix="个"
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="总销量"
                  value={shop.stats?.totalSales || 0}
                  suffix="件"
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="订单数量"
                  value={shop.stats?.totalOrders || 0}
                  suffix="单"
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="关注数"
                  value={shop.stats?.followers || 0}
                  suffix="人"
                />
              </Col>
            </Row>
          </Card>

          {/* 联系信息 */}
          {shop.contact && (
            <Card title="联系信息">
              <Space direction="vertical" style={{ width: '100%' }}>
                {shop.contact.phone && (
                  <div><PhoneOutlined /> {String(shop.contact.phone)}</div>
                )}
                {shop.contact.email && (
                  <div><MailOutlined /> {String(shop.contact.email)}</div>
                )}
                {shop.contact.address && (
                  <div><EnvironmentOutlined /> {String(shop.contact.address)}</div>
                )}
                {shop.contact.workingHours && (
                  <div><ClockCircleOutlined /> {String(shop.contact.workingHours)}</div>
                )}
              </Space>
            </Card>
          )}
        </Col>
      </Row>

      {/* 详细信息标签页 */}
      <Card>
        <Tabs defaultActiveKey="products">
          <TabPane tab="店铺商品" key="products">
            <Table
              columns={productColumns}
              dataSource={products}
              rowKey="_id"
              loading={loadingProducts}
              pagination={{
                pageSize: 10,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
            />
          </TabPane>

          <TabPane tab="店铺公告" key="announcement">
            <Card>
              {shop.announcement ? (
                <Paragraph>{String(shop.announcement)}</Paragraph>
              ) : (
                <Text type="secondary">暂无店铺公告</Text>
              )}
            </Card>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default ShopDetail;
